﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace syc.ZhiJian
{
    public partial class FileUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            UploadFile(fupInput);
        }

        internal readonly string AllowExt = "xls";
        /// <summary>
        /// 检测扩展名的有效性
        /// </summary>
        /// <param name="sExt">文件名扩展名</param>
        /// <returns>如果扩展名有效,返回true,否则返回false.</returns>
        bool CheckValidExt(string sExt)
        {
            bool flag = false;
            string[] aExt = AllowExt.Split('|');
            foreach (string filetype in aExt)
            {
                if (filetype.ToLower() == sExt.Replace(".", ""))
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }

        private void UploadFile(System.Web.UI.WebControls.FileUpload Fupload)
        {
            //文件上传函数
            try
            {
                if (Fupload.HasFile)
                {
                    //判断文件格式
                    string sExt = Fupload.FileName.Substring(Fupload.FileName.LastIndexOf(".")).ToLower();
                    if (!CheckValidExt(sExt))
                    {
                        lblMsg.Text = "(原图片文件格式不正确！支持的格式有[ " + AllowExt + " ])";
                        return;
                    }
                    //判断文件大小
                    int intFileLength = Fupload.PostedFile.ContentLength;
                    if (intFileLength > 1000 * 1000)
                    {
                        this.lblMsg.Text = "文件大于1M，不能上传！";
                        return;
                    }
                    Random ran = new Random();
                    string UpDir = "/ZhiJian/模板"; //上传目录
                    if (!Directory.Exists(Server.MapPath(UpDir)))
                    {
                            return; //如果创建失败则返回
                    }
                        //上传文件重命名：时间+三位随机数
                        string fileName = UpDir + "/" + "产品质量证明书";
                        fileName = fileName + sExt;
                        Fupload.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(fileName));
                        lblMsg.Text = fileName + "上传成功！";
                    
                }
                else
                    lblMsg.Text = "请选择文件！";
                return;
            }
            catch
            {
                lblMsg.Text = "发生错误，请重新上传文件！";
            }
        }
    }
    
}
